package com.xtm.exercise.base.B01cookie;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 *
 * Cookie快速入门
 *
 */

@WebServlet("/cookieDemo1")
public class CookieDemo1 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.创建Cookie对象
        Cookie c = new Cookie("msg","hello");
        //2.发送Cookie
        response.addCookie(c);
        //3. 获取Cookie
        Cookie[] cs = request.getCookies();
        //获取数据，遍历Cookies
        if(cs != null){
            for (Cookie c1 : cs) {
                String name = c1.getName();
                String value = c1.getValue();
                System.out.println(name+":"+value);
            }
        }

        //1.创建Cookie对象
//        Cookie c1 = new Cookie("msg","hello");
//        Cookie c2 = new Cookie("name","zhangsan");
//        //2.发送Cookie
//        response.addCookie(c1);
//        response.addCookie(c2);

        //1.创建Cookie对象
//        Cookie c1 = new Cookie("msg","setMaxAge");
//        //2.设置cookie的存活时间
//        //c1.setMaxAge(30);//将cookie持久化到硬盘，30秒后会自动删除cookie文件
//        //c1.setMaxAge(-1);
//        //c1.setMaxAge(300);
//        c1.setMaxAge(0);//删除Cookie
//        //3.发送Cookie
//        response.addCookie(c1);

        //1.创建Cookie对象
        Cookie c1 = new Cookie("msg","你好");
        //设置path，让当前服务器下部署的所有项目共享Cookie信息
        c1.setPath("/");

        //3.发送Cookie
        response.addCookie(c1);

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
